package com.guiwu.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

@Data
@TableName("item")
public class Item {
    @TableId(type = IdType.AUTO)
    private Long id;
    private String name;
    private String description;
    private Long categoryId;
    private BigDecimal price;
    private LocalDate purchaseDate;
    private LocalDateTime createdAt;
    private LocalDateTime updatedAt;
    private Long userId;

    @TableField(exist = false)
    private Category category;

    /**
     * 计算使用天数
     */
    public Long getUsageDays() {
        if (purchaseDate == null) {
            return 0L;
        }
        long days = ChronoUnit.DAYS.between(purchaseDate, LocalDate.now());
        return Math.max(days, 1L); // 至少算1天
    }

    /**
     * 计算日均价格
     */
    public BigDecimal getDailyPrice() {
        if (price == null || price.compareTo(BigDecimal.ZERO) <= 0) {
            return BigDecimal.ZERO;
        }
        Long usageDays = getUsageDays();
        if (usageDays <= 0) {
            return price;
        }
        return price.divide(BigDecimal.valueOf(usageDays), 2, RoundingMode.HALF_UP);
    }

    /**
     * 获取分类名称
     */
    public String getCategoryName() {
        return category != null ? category.getName() : "未分类";
    }
}